package com.pdd.cloud.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.pdd.cloud.zuul.enums.WebResultEmun;
import com.pdd.commons.entity.vo.AccountInfo_Vo;
import com.pdd.commons.response.ResponseEntity;
import com.pdd.commons.utils.AccountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**  
* @ClassName: ZuulFilter  
* @Description: TODO(这里用一句话描述这个类的作用)  
* @author laizejun  
* @date 2018年10月25日  
*    
*/
@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

	@Autowired
    private AccountUtil accountUtil;
	
	@Override
	public boolean shouldFilter() {
		//共享RequestContext，上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String uri = request.getRequestURI();
        //添加不需要认证的页面路径
        String[] notAuthPath = {
        		"/api/article/tourist",
				"/api/account/tourist"
		};
        for (String auth : notAuthPath) {
			if(uri.indexOf(auth)>-1) {
				return false;
			}
		}
		return true;
	}

	
	@Override
	public Object run() throws ZuulException {
		AccountInfo_Vo accountInfo_vo=accountUtil.getLoginInfo();
		if(accountInfo_vo==null){
			//共享RequestContext，上下文对象
			RequestContext requestContext = RequestContext.getCurrentContext();
			//不加响应头返回前端乱码
			ResponseEntity entity=new ResponseEntity();
			entity.setCode(WebResultEmun.LOGIN_INFO_NOT_EXISTS.getCode());
			entity.setMessage(WebResultEmun.LOGIN_INFO_NOT_EXISTS.getMsg());
			entity.setData(null);
			entity.setSuccess(WebResultEmun.LOGIN_INFO_NOT_EXISTS.isSuccess());
			requestContext.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
			requestContext.setSendZuulResponse(false);
			requestContext.setResponseBody(JSON.toJSONString(entity));
		}
        return null;
	}
	

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}
}
